#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
扫描工作线程
负责后台扫描任务的执行
"""

import os
import threading
from tkinter import messagebox


class ScanWorkers:
    """扫描工作线程混入类"""
    
    def scan_temp(self):
        """扫描临时文件"""
        self.run_scan_task("扫描临时文件中...", self._scan_temp_worker)
    
    def scan_duplicates(self):
        """扫描重复文件"""
        self.run_scan_task("查找重复文件中...", self._scan_duplicates_worker)
    
    def scan_large(self):
        """扫描大文件"""
        self.run_scan_task("查找大文件中...", self._scan_large_worker)
    
    def scan_dev_dirs(self):
        """扫描开发目录"""
        self.run_scan_task("检测开发目录中...", self._scan_dev_worker)
    
    def run_scan_task(self, status_text, worker_func):
        """运行扫描任务"""
        path = self.path_var.get()
        
        if not os.path.exists(path):
            messagebox.showerror("错误", "路径不存在！")
            self.add_log(f"[ERROR] 扫描失败: 路径不存在 - {path}", 'error')
            return
        
        if not os.access(path, os.R_OK):
            messagebox.showerror("权限错误", f"没有权限访问目录: {path}\n请以管理员身份运行程序或选择其他目录")
            self.add_log(f"[ERROR] 扫描失败: 没有读取权限 - {path}", 'error')
            return
        
        if not os.path.isdir(path):
            messagebox.showerror("错误", "请选择一个有效的目录！")
            self.add_log(f"[ERROR] 扫描失败: 不是有效目录 - {path}", 'error')
            return
            
        self.status_var.set(status_text)
        self.progress['value'] = 0
        self.add_log(f">> 开始{status_text[:-3]}: {path}", 'info')
        
        try:
            test_items = list(os.listdir(path))
            self.add_log(f">> 目录访问正常，发现 {len(test_items)} 个项目", 'info')
        except PermissionError as e:
            messagebox.showerror("权限错误", f"无法列出目录内容: {path}\n错误: {str(e)}\n\n请以管理员身份运行程序！")
            self.add_log(f"[ERROR] 权限不足: {str(e)}", 'error')
            return
        except Exception as e:
            messagebox.showerror("错误", f"访问目录时发生错误: {str(e)}")
            self.add_log(f"[ERROR] 目录访问错误: {str(e)}", 'error')
            return
        
        thread = threading.Thread(target=worker_func, args=(path,))
        thread.daemon = True
        thread.start()
    
    def _scan_temp_worker(self, path):
        """临时文件扫描工作线程"""
        try:
            temp_files = self.core.scan_temp_files(path, self.update_progress, self.update_status)
            self.root.after(0, self._update_temp_results, temp_files)
        except Exception as e:
            self.root.after(0, self._handle_scan_error, "临时文件扫描", str(e))
    
    def _scan_duplicates_worker(self, path):
        """重复文件扫描工作线程"""
        try:
            duplicates = self.core.find_duplicate_files(path, self.update_progress, self.update_status)
            self.root.after(0, self._update_dup_results, duplicates)
        except Exception as e:
            self.root.after(0, self._handle_scan_error, "重复文件扫描", str(e))
    
    def _scan_large_worker(self, path):
        """大文件扫描工作线程"""
        try:
            large_files = self.core.find_large_files(path, self.update_progress, self.update_status)
            self.root.after(0, self._update_large_results, large_files)
        except Exception as e:
            self.root.after(0, self._handle_scan_error, "大文件扫描", str(e))
    
    def _scan_dev_worker(self, path):
        """开发目录扫描工作线程"""
        try:
            # 立即更新状态，让用户知道开始工作了
            self.root.after(0, self.update_status, "初始化开发目录扫描...")
            
            dev_dirs = self.core.scan_dev_directories(path, self.update_progress, self.update_status)
            self.root.after(0, self._update_dev_results, dev_dirs)
        except Exception as e:
            self.root.after(0, self._handle_scan_error, "开发目录扫描", str(e))

    def add_log_safe(self, message, level='info'):
        """线程安全的日志添加"""
        self.root.after(0, self.add_log, message, level)